package backtrack;

import java.util.ArrayList;
import java.util.List;

public class L216 {

    private static List<List<Integer>> result = new ArrayList<>();
    private static List<Integer> path = new ArrayList<>();

    public static void main(String[] args) {
        System.out.println(combinationSum3(3, 7));
    }

    public static List<List<Integer>> combinationSum3(int k, int n) {
        backtracking(k, n, 1, 0);
        return result;
    }

    private static void backtracking(int k, int n, int begin, int sum) {
        //剪枝
        if (sum > n) {
            return;
        }
        //终止条件
        if (path.size() == k) {
            if (sum == n) result.add(new ArrayList<>(path));
            return;
        }
        //剪枝
        for (int i = begin; i <= 9 - (k - path.size()) + 1; i++) {
            path.add(i);
            backtracking(k, n, i + 1, sum + i);
            path.remove(path.size() - 1);
        }
    }
}
